// SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

#include "demo.h"

#include "common/common.h"
#include "common/actionmanager/actionmanager.h"
#include "common/actionmanager/actioncontainer.h"
#include "services/window/windowservice.h"
#include <ui/mainwindow.h>

#include "base/abstractwidget.h"
#include "base/abstractaction.h"
#include "base/abstractmenu.h"

#include <QAction>
#include <QIcon>
#include <QMainWindow>

class MainWindowDeleter : public QWidget
{
public:
    MainWindowDeleter(Zeal::WidgetUi::MainWindow *mainWindow, QWidget *parent = nullptr) : mw(mainWindow), QWidget(parent) {}
    ~MainWindowDeleter() { mw->setParent(nullptr); }; //按照zeal原逻辑，如果直接释放mw会导致崩溃，因此需要手动将mw的父对象置为nullptr，关闭应用时，让系统自动回收。
private:
    Zeal::WidgetUi::MainWindow *mw = nullptr;
};

void Demo::initialize()
{
}

bool Demo::start()
{
    auto windowService = dpfGetService(dpfservice::WindowService);

    app = new Zeal::Core::Application(qApp);
    auto mainWindow = app->mainWindow();

    MainWindowDeleter *widget = new MainWindowDeleter(mainWindow);
    QVBoxLayout *layout = new QVBoxLayout(widget);
    layout->addWidget(mainWindow);
    layout->setContentsMargins(0, 0, 0, 0);

    if (windowService) {
        QAction *action = new QAction("zeal", this);
        auto zealWindow = new AbstractWidget(widget);
        windowService->registerWidget("zeal", zealWindow);

        action->setIcon(QIcon(QStringLiteral(":/icons/logo/icon.png")));
        // Add navigation to navigationbar
        windowService->addNavigationItem(new AbstractAction(action), Priority::lowest);
        
        // activated when triggered navigation
        connect(action, &QAction::triggered, this, [=](){
            // show mainwindow
            windowService->showWidgetAtPosition("zeal", dpfservice::Position::Central, true);
        }, Qt::DirectConnection);
    }

    return true;
}

dpf::Plugin::ShutdownFlag Demo::stop()
{
    return Sync;
}
